package osmedile.intellij.util.psi;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.annotations.Nullable;
import osmedile.intellij.util.RegexUtil;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Olivier Smedile
 * @version $Id: File Header.java 3 2008-03-11 08:52:55Z osmedile $
 */
public class SimpleAllower implements Allower {

    /**
     * key: a template replacement variable like "$A_MinMax_P_max$"
     * value: value of the annotation parameter
     */
    private Collection<String> variantVars;

// --------------------------- CONSTRUCTORS ---------------------------

    public SimpleAllower(Collection<String> variantVars) {
        this.variantVars = variantVars;
    }

// --------------------- GETTER / SETTER METHODS ---------------------

    public Collection<String> getVariantVars() {
        return variantVars;
    }

    public void setVariantVars(Collection<String> variantVars) {
        this.variantVars = variantVars;
    }

// -------------------------- OTHER METHODS --------------------------

    public boolean allowVariant(@Nullable PsiElement content, @Nullable PsiElement eltToFind,
                                Map<PsiElement, PsiElement> replacement) {
        if (eltToFind instanceof PsiReferenceExpression) {
            String qName = ((PsiReferenceExpression) eltToFind).getQualifiedName();

            if (variantVars.contains(qName)) {
                replacement.put(content, eltToFind);
                return true;
            }
        } else if (eltToFind instanceof PsiLiteralExpression && content instanceof PsiLiteralExpression) {
            String textToFind = eltToFind.getText();
            String textContent = content.getText();
            textToFind = RegexUtil.inhibitRegexChars(textToFind);
            textToFind = RegexUtil.transforPattern(textToFind, getVariantVars());

            Pattern p = Pattern.compile(textToFind);
            Matcher match = p.matcher(textContent);
            if (match.find()) {
                replacement.put(content, eltToFind);
                return true;
            }
        }
        return content.getText().trim().equalsIgnoreCase(eltToFind.getText().trim());

//        PsiReference ref1 = content.getReference();
//        if (ref1 != null) {
//            PsiReference ref2 = eltToFind.getReference();
//            if (ref2 == null) {
//                return false;
//            }
//            PsiElement resolved1 = ref1.resolve();
//            PsiElement resolved2 = ref2.resolve();
//            if (!Comparing.equal(resolved1, resolved2) && (eltComparator == null ||
//                    eltComparator.compare(resolved1, resolved2) != 0)) {
//                return false;
//            }
//        }
//        return true;
    }
}